import { defineStore } from 'pinia'

// 用户信息接口
export interface User {
  id: number
  username: string
  email: string
  phone: string
  avatar?: string
  nickname?: string
}

// 用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    isLoggedIn: false,
    token: localStorage.getItem('token') || null
  }),

  getters: {
    // 获取用户信息
    getUserInfo: (state) => state.user,
    // 检查是否已登录
    checkIsLoggedIn: (state) => state.isLoggedIn && state.user !== null,
    // 获取用户头像
    getUserAvatar: (state) => state.user?.avatar || '/default-avatar.svg',
    // 获取用户昵称或用户名
    getDisplayName: (state) => state.user?.nickname || state.user?.username || '用户'
  },

  actions: {
    // 登录
    async login(credentials: { username: string; password: string }) {
      try {
        // 模拟登录API调用
        // 这里应该调用真实的登录API
        const mockUser: User = {
          id: 1,
          username: credentials.username,
          email: `${credentials.username}@example.com`,
          phone: '138****8888',
          nickname: credentials.username,
          avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-4.0.3&w=150&h=150&fit=crop&crop=face'
        }

        const mockToken = 'mock-jwt-token-' + Date.now()

        // 保存用户信息和token
        this.user = mockUser
        this.isLoggedIn = true
        this.token = mockToken

        // 持久化存储
        localStorage.setItem('token', mockToken)
        localStorage.setItem('user', JSON.stringify(mockUser))

        return { success: true, user: mockUser }
      } catch (error) {
        return { success: false, error: '登录失败，请检查用户名和密码' }
      }
    },

    // 注册
    async register(userData: { username: string; password: string; email: string; phone: string }) {
      try {
        // 模拟注册API调用
        const newUser: User = {
          id: Date.now(),
          username: userData.username,
          email: userData.email,
          phone: userData.phone,
          nickname: userData.username
        }

        const mockToken = 'mock-jwt-token-' + Date.now()

        // 注册成功后自动登录
        this.user = newUser
        this.isLoggedIn = true
        this.token = mockToken

        // 持久化存储
        localStorage.setItem('token', mockToken)
        localStorage.setItem('user', JSON.stringify(newUser))

        return { success: true, user: newUser }
      } catch (error) {
        return { success: false, error: '注册失败，请稍后重试' }
      }
    },

    // 登出
    logout() {
      this.user = null
      this.isLoggedIn = false
      this.token = null

      // 清除持久化存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    // 初始化用户状态（从localStorage恢复）
    initializeAuth() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')

      if (token && userStr) {
        try {
          const user = JSON.parse(userStr)
          this.user = user
          this.isLoggedIn = true
          this.token = token
        } catch (error) {
          // 如果解析失败，清除无效数据
          this.logout()
        }
      }
    },

    // 更新用户信息
    updateUserInfo(updates: Partial<User>) {
      if (this.user) {
        this.user = { ...this.user, ...updates }
        localStorage.setItem('user', JSON.stringify(this.user))
      }
    }
  }
})

// 主存储（保留原有的，以防其他地方使用）
export const useMainStore = defineStore('main', {
  state: () => ({
    // 初始状态
  }),
  getters: {
    // 计算属性
  },
  actions: {
    // 方法
  }
})